package com.thinkbig.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Welcome extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String END_OF_LINE = "<br>";

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext context = getServletContext();
        Integer count = (Integer) context.getAttribute("counter");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        context.setAttribute("counter", count);
        String encoding = resp.getCharacterEncoding();
        resp.setContentType(String.format("text/html;charset=%s", encoding));
        PrintWriter out = resp.getWriter();
        out.println(String.format("The total page view is: %s%s", count.toString(), END_OF_LINE));
        String user = req.getParameter("user");
        if (user == null || user.length() == 0) {
            out.println("Please input your name before submitting!");
        } else {
            String welcome = "Welcome you:" + user;
            out.println(welcome + END_OF_LINE);
        }
        out.close();

    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }

}
